<?php

namespace addons\TfFutures\api\controllers;

use addons\TfFutures\common\models\Member;
use addons\TfFutures\common\models\Symbol;
use addons\TfFutures\services\OrderService;
use addons\TfFutures\common\models\OrderReason;
use Yii;
use common\helpers\ResultDataHelper;
use api\controllers\OnAuthController;
use addons\TfFutures\common\models\Order;
use common\helpers\ExcelHelper;
use trade\common\service\KlineService;

class OrderController extends OnAuthController
{
    public $modelClass = Order::class;
    public $modelClass1 = OrderReason::class;


    /**
     * 订单列表
     * @return string
     * 当日交易
     */
    public function actionOlist()
    {
        if (!Yii::$app->request->isGet) {
            return ResultDataHelper::api(304, 'access done!');
        }
        $uid = Yii::$app->user->identity->member_id;
        if (empty($uid)) {
            return ResultDataHelper::api(422, '用户id不能为空');
        }
        //type为1是按合约查询
        $type =Yii::$app->request->get('type');
        $where = ['>', 'id', 0];
        $model = $this->modelClass::find()
            ->where($where)
            ->andWhere(['status' => 1, 'member_id' => $uid]);
        $models = $model->all();
        if($models->state=='平仓'){
            $model = $model
            ->andWhere(['>=','close_time',date('Y-m-d 00:00:00')]);
        }else{
            $model = $model
            ->andWhere(['>=','open_time',date('Y-m-d 00:00:00')]);
        }
        if($type == 1){
            $model = $model
                ->orderBy('symbol desc')
                ->asArray()
                ->all();
        }else{
            $model = $model
                ->orderBy('created_at desc')
                ->asArray()
                ->all();
        }
        foreach ($model as $k => $v) {
            $symbol = Symbol::find()->where(['code' => $v['symbol']])->one();
            $model[$k]['symbol_detail'] = $symbol;
            //返回开平仓的时间
            if($v['state']=='持仓'){
                $model[$k]['open'] = $v['open_time'];
            }else{
                $model[$k]['open'] = $v['close_time'];
            }
            $model[$k]['created_at'] = date('Y-m-d H:i:s', $model[$k]['created_at']);
            $model[$k]['updated_at'] = date('Y-m-d H:i:s', $model[$k]['updated_at']);
        }

        return ResultDataHelper::api(200, 'ok', $model);
    }
    /**
     * 订单列表
     * @return string
     */
    public function actionList()
    {
        if (!Yii::$app->request->isGet) {
            return ResultDataHelper::api(304, 'access done!');
        }
        $uid = Yii::$app->user->identity->member_id;
        if (empty($uid)) {
            return ResultDataHelper::api(422, '用户id不能为空');
        }
        $state =strtolower(Yii::$app->request->get('state'));
        switch ($state) {
            case 'hold':
                $where = ['state' => '持仓'];
                break;
            case 'end':
                $where = ['state' => '平仓'];
                break;
            default:
                $where = ['>', 'id', 0];
                break;
        }
        $model = $this->modelClass::find()
            ->where($where)
            ->andWhere(['status' => 1, 'member_id' => $uid])
            ->orderBy('created_at desc')
            ->asArray()
            ->all();
        foreach ($model as $k => $v) {
            $symbol = Symbol::find()->where(['code' => $v['symbol']])->one();
            $model[$k]['symbol_detail'] = $symbol;
            $model[$k]['created_at'] = date('Y-m-d H:i:s', $model[$k]['created_at']);
            $model[$k]['updated_at'] = date('Y-m-d H:i:s', $model[$k]['updated_at']);
        }

        return ResultDataHelper::api(200, 'ok', $model);
    }

    /**
     * 交易订单
     * @return string
     */
    public function actionTransaction()
    {
        if (!Yii::$app->request->isGet) {
            return ResultDataHelper::api(304, 'access done!');
        }
        $uid = Yii::$app->user->identity->member_id;
        if (empty($uid)) {
            return ResultDataHelper::api(422, '用户id不能为空');
        }
        $model = $this->modelClass::find()
            ->andWhere(['status' => 1, 'member_id' => $uid])
            ->asArray()
            ->all();
        foreach ($model as $k => $v) {
            $model[$k]['created_at'] = date('Y-m-d h-i-s', $v['created_at']);
        }
        return ResultDataHelper::api(200, 'ok', $model);
    }

    /**
     *订单价位模式开仓
     **/
    public function actionOpenWithPrice()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'access done');
        }

        $postdate = Yii::$app->request->post();
        list($type, $status) = OrderService::OpenWithPrice(Yii::$app->user->identity->member_id,
            $postdate['symbol_id'], $postdate['cmd'], $postdate['rise_fall'],
            $postdate['price'], $postdate['volume'],$postdate['stop_profit_price'],
            $postdate['stop_loss_price'], $postdate['expiration'],$postdate['conditionsprice'], $postdate['price_type'],$postdate['type']);

        if (!$type) {
            return ResultDataHelper::api(422, $status);
        }

        return ResultDataHelper::api(200, '开仓成功');
    }

    /**
     * 点位模式开仓
     */
    public function actionOpenWithPoint()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'Access done');
        }
        $postdate = Yii::$app->request->post();
        list($type, $status) = OrderService::OpenWithPoint(Yii::$app->user->identity->member_id,
            $postdate['symbol_id'], $postdate['cmd'], $postdate['rise_fall'],
            $postdate['price'], $postdate['volume'], $postdate['stop_profit_point'],
            $postdate['stop_loss_point'], $postdate['expiration']);
        if (!$type) {
            return ResultDataHelper::api(422, $status);
        }

        return ResultDataHelper::api(200, '开仓成功');
    }

    /**
     * 平仓
     */
    public function actionCloseOrder()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'access done');
        }
        $postdate = Yii::$app->request->post();
        list($status, $m) = OrderService::OrderClose($postdate['orderid'], $postdate['price'],
            '手动平仓');
        if (!$status) {
            return ResultDataHelper::api(422, '平仓失败', $m);
        }

        return ResultDataHelper::api(200, '平仓成功');
    }

    /**
     * 修改订单
     */
    public function actionUpdateWithPrice()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'access done');
        }
        $postdate = Yii::$app->request->post();
        list($status, $m) = OrderService::UpdateWithPrice($postdate['orderid'], $postdate['price'],
            $postdate['stop_profit_price'], $postdate['stop_loss_price'], $postdate['expiration']);
        if (!$status && !$m) {
            return ResultDataHelper::api(422, '修改失败', $m);
        }

        return ResultDataHelper::api(200, '修改成功');
    }

    /**
     * 全部平仓
     */
    public function actionCloseAll()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'Access done!');
        }
        $uid = Yii::$app->user->identity->member_id;
        //获取用户全部
        $order = Order::find()
            ->where(['=', 'member_id', $uid])
            ->andWhere(['=', 'state', '持仓'])
            ->all();
        if (empty($order)) {
            return ResultDataHelper::api(422, '用户没有订单');
        }

        foreach ($order as $item) {
            $Symbol = Symbol::findOne(['code2'=>$item->symbol]);
            $kline                   = new KlineService();
            $newPrice                = $kline->loadTicekt($Symbol->code,'tf_futures_trade');
            if (empty($newPrice)) {
                return ResultDataHelper::api(422, '最新价格获取失败');
            }
            list($status, $m) = OrderService::OrderClose($item->id);
        }
        if (!$status) {
            return ResultDataHelper::api(422, '全部平仓失败', $m);
        }

        return ResultDataHelper::api(200, '全部平仓成功');
    }

    /**
     * 快捷反手 平掉当前,并且买一手相反的
     */
    public function actionBankHand()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'access done');
        }
        $postdate = Yii::$app->request->post();
        list($status, $m) = OrderService::OrderClose($postdate['orderid'], $postdate['price'],
            '手动平仓');
        if (!$status) {
            return ResultDataHelper::api(422, '平仓失败', $m);
        }
        //需要反手的订单
        $order = Order::findOne($postdate['orderid']);


        if (isset($order->cmd)) {
            $cmd = $order->cmd;
        } else {
            $cmd = 'NOW';
        }
        $order->rise_fall = $order->rise_fall == 'RISE'
            ? 'FALL'
            : 'RISE';
        $symbol=Symbol::findOne(['code2'=>$order->symbol]);
        //获取最新价格
        $newPrice                  = new KlineService();
        $newPrice                  = $newPrice->loadTicekt($symbol->code,'tf_futures_trade');
        if (empty($newPrice['price'])) {
            return ResultDataHelper::api(422, '最新价格获取失败');
        }
        if (empty($order->stop_profit_point)) {
            //价位模式开仓
            list($type, $status) = OrderService::OpenWithPrice($order->member_id,
                $order->symbol, $cmd, $order->rise_fall, $newPrice['price'], $order->volume,
                $order->stop_profit_price, $order->stop_loss_price, $order->expiration);
        } else {
            //点位模式开仓
            list($type, $status) = OrderService::OpenWithPoint($order->member_id,
                $order->symbol, $cmd, $order->rise_fall, $newPrice->price, $order->volume,
                $order->stop_profit_point, $order->stop_loss_point, $order->expiration);
        }
        if (!$type) {
            return ResultDataHelper::api(422, $status);
        }

        return ResultDataHelper::api(200, '开仓成功');
    }

    /**
     * 结算列表
     * @return string
     */
    public function actionCounts()
    {
        if (!Yii::$app->request->isGet) {
            return ResultDataHelper::api(304, 'access done!');
        }
        $uid = Yii::$app->user->identity->member_id;
        if (empty($uid)) {
            return ResultDataHelper::api(422, '用户id不能为空');
        }
        $model = $this->modelClass::find();
        $time = Yii::$app->request->get('time',null);
        $times = Yii::$app->request->get('times',null);
        $type = Yii::$app->request->get('type',null);
        $where['state'] = '平仓';
        $where['status'] = 1;
        $where['member_id'] = $uid;
        $model = $this->modelClass::find()
            ->where($where);
        if(empty($type)) {
            $model = $model->andWhere(['>=','open_time',$time.' 00:00:00']);
        }
        if(!empty($time && $times)) {
            $model = $model->andWhere(['>=','open_time',$time.' 00:00:00'])->andWhere(['<=','open_time',$times.' 00:00:00']);
        } elseif (!empty($time)) {
            $model = $model->andWhere(['>=','open_time',$time.' 00:00:00']);
        } elseif (!empty($times)) {
            $model = $model->andWhere(['<=','open_time',$times.' 00:00:00']);
        }
        $model = $model->asArray()->all();
        if(empty($model)) {
            return ResultDataHelper::api('422','暂无结算订单');
        }
        foreach ($model as $k => $v) {
            $symbol = Symbol::find()->where(['code2' => $v['symbol']])->one();
            $model[$k]['symbol_detail'] = $symbol;
            $model[$k]['created_at'] = date('Y-m-d H:i:s', $model[$k]['created_at']);
            $model[$k]['updated_at'] = date('Y-m-d H:i:s', $model[$k]['updated_at']);
        }

        return ResultDataHelper::api(200, 'ok', $model);
    }

    /**
     * 查询用户结算单详情
     */
    public function actionLement()
    {
        if (!Yii::$app->request->isGet) {
            return ResultDataHelper::api(304, 'access done!');
        }
        $uid = Yii::$app->user->identity->member_id;
        if (empty($uid)) {
            return ResultDataHelper::api(422, '用户id不能为空');
        }
        $where['state'] = '平仓';
        $model = $this->modelClass::find()
            ->where($where)
            ->andWhere(['status' => 1, 'member_id' => $uid])
            ->orderBy('close_time desc')
            ->asArray()
            ->all();
        foreach ($model as $k => $v) {
            $model[$k]['created_at'] = date('Y-m-d H:i:s', $model[$k]['created_at']);
            $model[$k]['updated_at'] = date('Y-m-d H:i:s', $model[$k]['updated_at']);
        }
        return ResultDataHelper::api(200, 'success', $model);

    }


    /**
     *获取用户资金概况
     **/
    public static function loadStatic($memberid, $money)
    {
        $order = Order::find()
            ->where(['member_id' => $memberid, 'state' => '持仓', 'status' => 1])
            ->select('sum(service_fee) as service_fee, sum(overfee) as overfee, sum(deposit) as deposit, sum(profit) as profit')
            ->one();
        $reason = OrderReason::find()
            ->where(['member_id' => $memberid, 'state' => '挂单', 'status' => 1])
            ->select('sum(service_fee) as service_fee, sum(deposit) as deposit')
            ->one();
        $results = [
            'order_service_fee' => $order->service_fee,//手续费
            'order_overfee' => $order->overfee,//过夜费/延期费
            'order_deposit' => $order->deposit,//保证金
            'order_profit' => $order->profit,//盈损
            'reason_service_fee' => $reason->service_fee,//手续费
            'reason_deposit' => $reason->deposit,//保证金
            'floatpl' => $order->profit,//浮动盈亏
            'networth' => bcadd($money, $order->profit, 4),//净值
        ];
        $results['riskrate'] = bcmul(bcdiv($results['networth'],
            bcadd($results['order_deposit'], $results['reason_deposit'], 4) == 0
                ? 1
                : bcadd($results['order_deposit'], $results['reason_deposit'], 4), 4), 100, 2);//风险率
        $results['blocked'] = bcsub($results['networth'],
            bcadd($results['order_deposit'], $results['reason_deposit'], 4), 4);

        return $results;
    }

    /**
     * 持仓总数
     */
    public function actionAllHold()
    {
        if (!Yii::$app->request->isGet) {
            return ResultDataHelper::api(403, 'access done');
        }
        $code = Yii::$app->request->get('code');
        if (empty($code)) {
            return ResultDataHelper::api(422, '产品code不能为空！');
        }
        $symbol = Symbol::find()
            ->where(['code' => $code])
            ->one();

        if (empty($symbol)) {
            return ResultDataHelper::api(422, '没有数据');
        }
        if ($symbol->status != 1) {
            return ResultDataHelper::api(422, '产品已经被禁用！');
        }
        //所有产品持仓总数
        $order = Order::find()
            ->select('sum(volume) as volume')
            ->where(['symbol' => $symbol->id, 'status' => 1, 'state' => '持仓'])
            ->one();
        if (empty($order)) {
            return ResultDataHelper::api(422, '没有数据');
        }

        return ResultDataHelper::api(200, 'success', $order->volume);
    }

    /**
     * 最大可买数
     * @return mixed
     */
    public function actionMaxHandle()
    {
        //获取用户资产信息
        $uid = Yii::$app->user->identity->member_id;
        list($member, $user_money) = Member::member($uid);
        $code = Yii::$app->request->post('code');
        if (empty($code)) {
            return ResultDataHelper::api(422, '产品code不能为空！');
        }
        $symbol = Symbol::find()->where(['=', 'code', $code])->asArray()->one();

        if (empty($symbol)) {
            return ResultDataHelper::api(422, '产品不存在！');
        }
        //计算净值
        $loadStatic = OrderService::loadStatic($uid, $user_money->price);
        $close_price = $symbol['deposit'] + $symbol['servicefee'];
        //最大可买数
        $number_num = bcdiv($loadStatic['networth'], $close_price);
        if (empty($number_num)) {
            return ResultDataHelper::api(422, '空');
        }
        $number = floor($number_num);

        return ResultDataHelper::api(200, 'success', $number);
    }
    /**
     * 导出
     * @param null $type (1:导出数据 2:导出模板)
     */
    public function actionExcel()
    {
    	if (!Yii::$app->request->isGet) {
            return ResultDataHelper::api(403, 'access done');
        }
		$uid = Yii::$app->user->identity->member_id;
		$status = Yii::$app->request->get('status');
        //表头
        $header = [
            ['产品名称', 'name', 'text'],
            ['买卖方向', 'rise_fall', 'text'],
            ['产品描述', 'desc', 'text'],
            ['合约量', 'contract_size', 'text'],
            ['交易时间', 'trade_time', 'text'],
            ['上架状态', 'on_sale', 'text'],
            ['产品点位单位', 'unit', 'text'],
            ['过夜费', 'overfee', 'text'],
            ['手续费', 'servicefee', 'text'],
            ['保证金', 'deposit', 'text'],
            ['最大止盈', 'maxrise', 'text'],
            ['最小止盈', 'minrise', 'text'],
            ['最大止损', 'maxlost', 'text'],
            ['最小止损', 'minlost', 'text'],
            ['滑点设置', 'risk', 'text'],
        ];
    	if($status=='持仓'){
    		//表数据
    		$model = $this
        	->modelClass::find()
        	->where(['member_id'=>$uid])
        	->andWhere(['state'=>$status])
        	->asArray()
        	->all();
    	}elseif($status=='委托'){
    		$model = $this
        	->modelClass1::find()
        	->where(['member_id'=>$uid])
        	->andWhere(['state'=>'挂单'])
        	->asArray()
        	->all();
    	}else{
    		return ResultDataHelper::api(422, '传值错误');
    	}
        // print_r($model);die;
        if (empty($model)) {
            return ResultDataHelper::api(422, '数据为空');
        }
        //excel数据
        foreach ($model as $item) {
        	$item['rise_fall'] = $item['rise_fall'] == 'FALL' ? '买跌':'买涨';
            $list[] = [
                'id'            => $item['id'],
                'name'          => $item['symbol_cn'],
                'rise_fall'     => $item['rise_fall'],
                'desc'          => $item['desc'],
                'contract_size' => $item['contract_size'],
                'trade_time'    => $item['trade_time'],
                'on_sale'       => $item['on_sale'],
                'unit'          => $item['unit'],
                'overfee'       => $item['overfee'],
                'servicefee'    => $item['servicefee'],
                'deposit'       => $item['deposit'],
                'maxrise'       => $item['maxrise'],
                'minrise'       => $item['minrise'],
                'maxlost'       => $item['maxlost'],
                'minlost'       => $item['minlost'],
                'risk'          => $item['risk'],
            ];
        }
        return ExcelHelper::exportData($list, $header);
    }


}